package com.netty.admin.security.service;

import com.netty.admin.service.UserService;
import com.netty.common.entity.bo.AuthUser;
import com.netty.common.entity.vo.LoginUser;
import com.netty.common.enums.ExceptionEnum;
import com.netty.common.exception.BizException;
import com.netty.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 * 
 */
@Component
public class LoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;



    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password) {
        // 用户验证
        Authentication authentication;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new BizException(ExceptionEnum.LOGIN_FAIL,"用户名或者密码错误");
            } else {
                throw new BizException(ExceptionEnum.ERROR,e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }


}
